//
//  GroupManagerVC.m
//  ChangChat
//
//  Created by Cocoa on 2019/10/15.
//  Copyright © 2019 yibai. All rights reserved.
//

#import "GroupManagerVC.h"
#import "GroupManagerHeaderView.h"
#import "YBContentModel.h"
#import "MineCell.h"
#import "YBApiManager+Chat.h"
#import "EVCPopInputView.h"
#import <LKDBHelper/LKDBHelper.h>
#import "AppDelegate.h"
#import <TZImagePickerController/TZImagePickerController.h>
#import "YBApiManager+Global.h"
#import "SwitchCell.h"

@interface GroupManagerVC ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, strong) UIImagePickerController * currentPickerController;
@property (nonatomic, strong) GroupManagerHeaderView *headView;
@end

@implementation GroupManagerVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self setupDatasource];
}
- (void)setupUI {
    self.title = @"群管理";
    self.headView = [GroupManagerHeaderView new];
    self.tableView.tableHeaderView = self.headView;
    [self.tableView layoutIfNeeded];
    [self.headView.actionBtn addTarget:self action:@selector(didClickUpdateAvatarBtnAction) forControlEvents:UIControlEventTouchUpInside];
    self.tableView.tableHeaderView = self.headView;
    self.tableView.separatorColor = UIColor.clearColor;
    [self.tableView customRegisterClassWithName:@"MineCell"];
    [self.tableView customRegisterClassWithName:@"SwitchCell"];
}
- (void)setupDatasource {
    YBContentModel *model = [YBContentModel new];
    model.title = @"群聊名称";
    model.rightText = self.group.name;
    model.icon = @"arrow_right";
    model.cellId = @"MineCell";
    
    [self.dataSource addObject:model];
    model = [YBContentModel new];
    model.title = @"禁言";
    model.selected = self.group.shutup;
    model.cellId = @"SwitchCell";
    [self.dataSource addObject:model];
    
    [self.tableView reloadData];
    [self.headView.iconImgView sd_setImageWithURL:self.group.avatar.toURL placeholderImage:UIImage.k_imgName(@"placeholder_user")];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YBContentModel *model = self.dataSource[indexPath.row];
    MineCell *cell = [tableView dequeueReusableCellWithIdentifier:model.cellId forIndexPath:indexPath];
    cell.model = model;
    cell.showBottomLine = YES;
    @weakify(self);
    if ([cell isKindOfClass:SwitchCell.class] == YES) {
        SwitchCell *sCell = (SwitchCell *)cell;
        [[[sCell.switchView rac_newOnChannel] takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(NSNumber * _Nullable x) {
            NSLog(@"x = %@",x);
            @strongify(self);
            [self didClickSwitchViewAction:sCell.switchView indexPath:indexPath];
        }];
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    YBContentModel *model = self.dataSource[indexPath.row];
        if ([model.title isEqualToString:@"群聊名称"] == YES) {
            [self didClickGroupNameCell];
        }
}

- (void)didClickGroupNameCell {
    @weakify(self);
    EVCPopInputView *popView = [EVCPopInputView popInputViewWithTitle:@"修改群名称" subTitle:nil placehold:@"请输入群名称" preset:self.group.name];
    [popView show];
    [popView clickButtonAction:^(NSInteger index, NSString *content) {
        if (index == 1) {
            @strongify(self);
            [self updateGroupNameActionWithNewName:content];
        }
    }];
}
- (void)updateGroupNameActionWithNewName:(NSString *)newName {
    [MBProgressHUD showActivityMessageInView:@""];
    @weakify(self);
    [[YBApiManager.shareManager updateGroupName:newName groupAvatar:@"" group_id:self.group.group_id] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [MBProgressHUD hideHUD];
        self.group.name = newName;
        [self.group updateToDB];
        [MBProgressHUD showTipMessageInView:@"修改成功" timer:1.0f];
        [[NSNotificationCenter defaultCenter] postNotificationName:notification_GroupChatInfo_updated object:self.group];
        YBContentModel *model = self.dataSource[0];
        model.rightText = newName;
        [self.tableView reloadData];
    } error:^(NSError * _Nullable error) {
        [MBProgressHUD hideHUD];
        if ([error isServerError]) {
            [MBProgressHUD showTipMessageInView:error.localizedDescription timer:1.0f];
        } else {
            [MBProgressHUD showTipMessageInView:@"网络错误，请重试" timer:1.0f];
        }
    }];
}

- (void)didClickSwitchViewAction:(UISwitch *)switchView indexPath:(NSIndexPath *)indexPath {
    YBContentModel *model = self.dataSource[indexPath.row];
    BOOL originValue = !switchView.isOn;
    @weakify(self);
    if (originValue == YES) {
        [[YBApiManager.shareManager groupEnableSendMsgWithGroupId:self.group.group_id] subscribeNext:^(id  _Nullable x) {
            @strongify(self);
//            [MBProgressHUD showTipMessageInView:@"解除禁言" timer:1.0f];
            self.group.shutup = NO;
            [self.group updateToDB];
            model.selected = NO;
        } error:^(NSError * _Nullable error) {
            [MBProgressHUD hideHUD];
            if ([error isServerError]) {
                [MBProgressHUD showTipMessageInView:error.localizedDescription timer:1.0f];
            } else {
                [MBProgressHUD showTipMessageInView:@"网络错误，请重试" timer:1.0f];
            }
            @strongify(self);
            [self.tableView reloadData];
        }];
    } else {
        
        [[YBApiManager.shareManager groupDisableSendMsgWithGroupId:self.group.group_id] subscribeNext:^(id  _Nullable x) {
//            [MBProgressHUD showTipMessageInView:@"禁言成功" timer:1.0f];
            @strongify(self);
            self.group.shutup = YES;
            model.selected = YES;
            [self.group updateToDB];
        } error:^(NSError * _Nullable error) {
            [MBProgressHUD hideHUD];
            if ([error isServerError]) {
                [MBProgressHUD showTipMessageInView:error.localizedDescription timer:1.0f];
            } else {
                [MBProgressHUD showTipMessageInView:@"网络错误，请重试" timer:1.0f];
            }
            @strongify(self);
            [self.tableView reloadData];
        }];
    }
}

- (void)didClickUpdateAvatarBtnAction {
    [self.view endEditing:YES];
    
    [LBXAlertAction showActionSheetWithTitle:@"选择图片" message:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitle:@[@"拍照",@"相册"] chooseBlock:^(NSInteger buttonIdx) {
        
        if (buttonIdx == 1) {
            [self obtainPhotoByCamera];
        } else if (buttonIdx == 2) {
            [self obtainPhotoFromAlbum];
        }
    }];
}

//打开相机
- (void)obtainPhotoByCamera
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController * imagePickerController = [[UIImagePickerController alloc] init] ;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera ;
        imagePickerController.delegate = self;
        imagePickerController.navigationBar.translucent = NO;
        imagePickerController.showsCameraControls=YES;
        imagePickerController.navigationBar.tintColor = [UIColor whiteColor];
        imagePickerController.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        _currentPickerController = imagePickerController;
        
        kAppDelegate.window.rootViewController.definesPresentationContext = YES;
        [kAppDelegate.window.rootViewController presentViewController:_currentPickerController  animated:YES completion:nil];
    }
}
#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:nil];
        
        [tzImagePickerVc showProgressHUD];
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        // save photo and get asset / 保存图片，获取到asset
        [[TZImageManager manager] savePhotoWithImage:image location:nil completion:^(PHAsset *asset, NSError *error) {
            if (error) {
                [tzImagePickerVc hideProgressHUD];
                NSLog(@"图片保存失败 %@",error);
            } else {
                [[TZImageManager manager] getCameraRollAlbum:NO allowPickingImage:YES needFetchAssets:NO completion:^(TZAlbumModel *model) {
                    [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:NO allowPickingImage:YES completion:^(NSArray<TZAssetModel *> *models) {
                        [tzImagePickerVc hideProgressHUD];
                        TZAssetModel *assetModel = [models firstObject];
                        if (tzImagePickerVc.sortAscendingByModificationDate) {
                            assetModel = [models lastObject];
                        }
                        if (1) { // 允许裁剪,去裁剪
                            TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initCropTypeWithAsset:assetModel.asset photo:image completion:^(UIImage *cropImage, id asset) {
                                [self uploadImage:cropImage];
                            }];
                            imagePicker.needCircleCrop = NO;
                            imagePicker.circleCropRadius = 100;
                            [self presentViewController:imagePicker animated:YES completion:nil];
                        }
                    }];
                }];
            }
        }];
    }
}

//打开相册
- (void)obtainPhotoFromAlbum
{
    TZImagePickerController *tz = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:6 delegate:nil];
    tz.allowTakePicture =
    tz.allowPickingOriginalPhoto =
    tz.allowPickingVideo = NO;
    tz.allowCrop = YES;
    //    tz.photoPreviewPageDidLayoutSubviewsBlock = ^(UICollectionView *collectionView, UIView *naviBar, UIButton *backButton, UIButton *selectButton, UILabel *indexLabel, UIView *toolBar, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel) {
    //        naviBar.height = 44;
    //        backButton.top = 0;
    //        backButton.left = 20;
    //        toolBar.height = 44;
    //        toolBar.bottom = ScreenHeight;
    //        doneButton.right = toolBar.width - 20;
    //        doneButton.top = 0;
    //    };
    //    NSInteger widthHeight = self.view.height - 2 * 44;
    //    NSInteger top = (self.view.height - widthHeight) / 2;
    //    NSInteger left = self.view.width/2 - widthHeight/2;
    //    tz.cropRect = CGRectMake(left, top, widthHeight, widthHeight);
    //    // 设置横屏下的裁剪尺寸
    //    tz.cropRectLandscape = CGRectMake((self.view.width - widthHeight) / 2, top, widthHeight, widthHeight);
    
    [tz setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        [self uploadImage:photos.firstObject];
    }];
    
    [self presentViewController:tz animated:YES completion:nil];
}

- (void)uploadImage:(UIImage *)image{
    [MBProgressHUD showActivityMessageInView:@"上传中..."];
    @weakify(self);
    
    YBApiManager *newApiM = YBApiManager.shareManager;
    [[newApiM uploadImgWithImage:image] subscribeNext:^(id  _Nullable x) {
        NSString *imgUrlStr = [[x objectForKey:@"data"] objectForKey:@"url"];
        @strongify(self);
        //        self.iconImgView.image = image;
        //        self.imgPath = imgUrlStr;
        [self updateGroupAvatarWithUrl:imgUrlStr img:image];
    } error:^(NSError * _Nullable error) {
        [MBProgressHUD hideHUD];
        if ([error isServerError]) {
            [MBProgressHUD showTipMessageInView:error.localizedDescription timer:1.0f];
        } else {
            [MBProgressHUD showTipMessageInView:@"网络错误，请重试" timer:1.0f];
        }
    }];
}

- (void)updateGroupAvatarWithUrl:(NSString *)newValue img:(UIImage *)img {
//    [self changeMyInfoWithAvatar:newValue username:nil nickname:nil bio:nil gender:nil birthday:nil region:nil complete:^{
//        kUsermanager.me.avatar = newValue;
//        self.userView.iconImgView.image = img;
//        [[NSNotificationCenter defaultCenter] postNotificationName:notification_Friend_Info_Changed object:kUsermanager.me];
//    }];
    @weakify(self);
    [[YBApiManager.shareManager updateGroupName:@"" groupAvatar:newValue group_id:self.group.group_id] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [MBProgressHUD hideHUD];
        [MBProgressHUD showTipMessageInView:@"修改成功" timer:1.0f];
        self.group.avatar = newValue;
        [self.group updateToDB];
        self.headView.iconImgView.image = img;
        [[NSNotificationCenter defaultCenter] postNotificationName:notification_GroupChatInfo_updated object:self.group];
    } error:^(NSError * _Nullable error) {
        [MBProgressHUD hideHUD];
        if ([error isServerError]) {
            [MBProgressHUD showTipMessageInView:error.localizedDescription timer:1.0f];
        } else {
            [MBProgressHUD showTipMessageInView:@"网络错误，请重试" timer:1.0f];
        }
    }];
}

@end
